<template>
    <view class="p20 ">
        <uv-form :model="formData" :rules="rules" ref="formRef" labelWidth="220rpx">
            <!-- 基本信息 -->
            <view class="form_con">
                <uv-form-item :required="true" label="乡镇名称" prop="TownCode" borderBottom>
                    <uv-input disabled v-model="formData.Town" placeholder="请选择乡镇" border="none"></uv-input>
                    <template v-slot:right>
                        <uv-icon name="arrow-right"></uv-icon>
                    </template>
                </uv-form-item>
                <uv-form-item :required="true" label="巡查对象ID" prop="ObjectId" borderBottom>
                    <uv-input disabled v-model="formData.ObjectId" placeholder="请选择巡查对象ID" border="none"></uv-input>
                </uv-form-item>
                <uv-form-item :required="true" label="巡查时间" prop="Xcsj" borderBottom @click="dateConfirm">
                    <uv-input :readonly="true" v-model="formData.Xcsj" placeholder="请选择巡查时间" border="none"></uv-input>
                    <template v-slot:right>
                        <uv-icon name="arrow-right"></uv-icon>
                    </template>
                </uv-form-item>
                <uv-form-item :required="true" label="巡查天气" prop="Xctq" borderBottom>
                    <uv-input clearable v-model="formData.Xctq" placeholder="请输入巡查天气" border="none"></uv-input>
                </uv-form-item>
                <uv-form-item label="位置" prop="Place" labelPosition="top" borderBottom>
                    <uv-textarea customStyle="margin-top: 20rpx;" height="200rpx" v-model="formData.Place"
                        placeholder="请选择位置"></uv-textarea>
                    <template v-slot:right>
                        <uv-icon @click="getLocation" size="40rpx" color="#547ff7" name="map-fill"></uv-icon>
                    </template>
                </uv-form-item>
                <uv-form-item :required="true" label="经度/纬度" prop="LonLat" border="none">
                    <uv-input :readonly="true" v-model="formData.LonLat" placeholder="请选择经度/纬度"
                        border="none"></uv-input>
                    <template v-slot:right>
                        <uv-image @click="getLocation" src="/static/img/map/dingwei.svg" width="50rpx"
                            height="50rpx"></uv-image>
                    </template>
                </uv-form-item>
            </view>


            <!-- 其他信息 -->
            <view class="form_con">
                <uv-form-item :required="true" label="填表人" prop="Tbr" borderBottom>
                    <uv-input clearable :suffixIconStyle="{ fontSize: '40rpx' }" v-model="formData.Tbr"
                        placeholder="请输入填表人姓名" border="none"></uv-input>
                </uv-form-item>
                <uv-form-item :required="true" label="巡查内容" prop="Xcnr" labelPosition="top" borderBottom>
                    <uv-textarea customStyle="margin-top: 20rpx;" height='188rpx' v-model="formData.Xcnr"
                        placeholder="请输入巡查内容"></uv-textarea>
                </uv-form-item>
                <uv-form-item label="现场处置及建议" prop="Xccz" labelPosition="top" borderBottom>
                    <uv-textarea customStyle="margin-top: 20rpx;" height='188rpx' v-model="formData.Xccz"
                        placeholder="请输入现场处置及建议"></uv-textarea>
                </uv-form-item>
                <uv-form-item label="巡查照片" prop="FileIds" border="none" labelPosition="top">
                    <lh-upload-img :list="formData.FileIds" @change="updateFile" :mount="3"
                        :formData="uploadFormData"></lh-upload-img>
                </uv-form-item>
            </view>
        </uv-form>
        <uv-button type="primary" v-if="formOperType != SYSFORMOPERTYPE.View" @click="submitForm"
            :loading="loading">提交报表</uv-button>
    </view>
    <uv-datetime-picker round="40rpx" ref="datetimePickerRef" v-model="dateValue" mode="datetime" itemHeight="88"
        @confirm="PickerConfirm"></uv-datetime-picker>
</template>

<script lang="ts" setup>
import { addXcxx_API, updateXcxx_API, XcxxLook_API } from '@/server/home'
import { SYSFORMOPERTYPE } from '@/utils/enum'
import dayjs from 'dayjs'
let objId = ''
const formOperType = ref()
onLoad((options) => {
    formOperType.value = options.optype || SYSFORMOPERTYPE.Add
    objId = options.id
    objId && initTask()
})
const rules = {
    TownCode: {
        required: true,
        message: '请选择乡镇',
        trigger: ['change', 'blur']
    },
    Xcry: {

        required: true,
        message: '请输入巡查人员',
        trigger: ['change', 'blur']
    },
    Xcsj: {

        required: true,
        message: '请选择巡查时间',
        trigger: ['change', 'blur']
    },
    Xctq: {

        required: true,
        message: '请输入巡查天气',
        trigger: ['change', 'blur']
    },
    Xcnr: {

        required: true,
        message: '请输入巡查内容',
        trigger: ['change', 'blur']
    },
    Lon: {
        rules: [{
            required: true,
            errorMessage: '请输入经度',
            trigger: ['change', 'blur']
        }, {
            validateFunction: function (rule, value, data, callback) {
                let lonReg =
                    /^-?(((\d|[1-9]\d|1[0-7]\d|0)\.\d{0,16})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,16}|180)$/i;
                if (!lonReg.test(value)) {
                    callback('请输入正确的经度')
                }
                return true
            }
        }]
    },
    Lat: {
        rules: [{
            required: true,
            errorMessage: '请输入纬度',
            trigger: ['change', 'blur']
        }, {
            validateFunction: function (rule, value, data, callback) {
                let latReg = /^-?([0-8]?\d{1}\.\d{0,16}|90\.0{0,16}|[0-8]?\d{1}|90)$/i;
                if (!latReg.test(value)) {
                    callback('请输入正确的纬度')
                }
                return true
            }
        }]
    },
    LonLat: {
        required: true,
        message: '请输入经纬度',
        trigger: ['change', 'blur']
    },
    Tbr: {

        required: true,
        message: '请输入填表人',
        trigger: ['change', 'blur']

    },
}
const formData = ref({
    Town: '',
    TownCode: '',
    Xctq: null,
    Place: '',
    Lon: null,
    Lat: null,
    LonLat: '',
    Xcsj: null,
    Xcry: '', //巡查人员
    ObjectId: '',
    Xcnr: '',
    Xccz: null,
    Tbr: '',
    Remark: '',
    FileIds: []
})
const uploadFormData = ref({
    TypeCode: "ZQSB",
    FKey: '',
})
const initTask = async () => {
    const res = await XcxxLook_API(objId)
    if (res.IsSuccess) {
        formData.value = res.Data
        formData.value.LonLat = Number(res.Data.Lon).toFixed(6) + '/' + Number(res.Data.Lat).toFixed(6);
        formData.value.Xcsj = res.Data.Xcsj?.replace("T", " ")
        uploadFormData.value.FKey = res.Data.Id;
        // //处理图片
        // if (formData.value.FileIds != null && formData.value.FileIds.length > 0) {
        //     formData.value.FileIds = formData.value.FileIds.map(item => {
        //         return import.meta.env.LH_FILE_BASEURLDZFZ + item
        //     });
        // }

    } else {
        uni.$uv.toast(res.Message)
    }
}
const datetimePickerRef = ref()
const dateValue = ref()
const dateConfirm = () => {
    datetimePickerRef.value?.open()
    //日期格式 转换时间戳
    dateValue.value = formData.value.Xcsj
        ? dayjs(formData.value.Xcsj).valueOf()
        : Number(new Date())
}
const PickerConfirm = (e) => {
    const data = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
    formData.value.Xcsj = data
}
const getLocation = () => {
    uni.showLoading({
        title: "定位中",
    })
    uni.getLocation({
        type: 'gcj02',
        geocode: true,
        isHighAccuracy: true,
        success: (res) => {
            console.log('当前位置：', res);
            formData.value.Lon = res.longitude;
            formData.value.Lat = res.latitude;
            formData.value.LonLat = Number(res.longitude).toFixed(6) + '/' + Number(res.latitude).toFixed(6);
            if (res.address) {
                formData.value.Place = res.address?.province + res.address?.city + res.address
                    ?.district + res.address?.street + res.address?.streetNum + res.address?.poiName
            }
        },
        fail(err) {
            uni.showToast({
                title: "获取位置失败",
            })
        },
        complete: () => {
            uni.hideLoading()
        },
    });
}

const updateFile = (e) => {
    console.log("e:", e);
}
const loading = ref()
const formRef = ref()
const submitForm = async () => {
    try {
        await formRef.value.validate();
        loading.value = true
        formData.value.Xcry = formData.value.Tbr;
        if (formData.value.FileIds.length == 0) {
            formData.value.FileIds = null;
        }
        let res
        if (formOperType.value == SYSFORMOPERTYPE.Edit) {
            res = await updateXcxx_API(formData.value, objId)
        } else {
            res = await addXcxx_API(formData.value)
        }
        if (res.IsSuccess) {
            uni.$uv.toast("提交成功")
            setTimeout(() => {
                loading.value = false;
                // uni.$emit('refresh-data')
                uni.navigateBack()
            }, 1000)
        } else {
            uni.$uv.toast(res.Message || '提交失败')
        }
    } catch (error) {
        loading.value = false;
    }
}
</script>

<style lang="scss" scoped>
page {
    background: #edf2fa;
}

.form_con {
    padding: 20rpx 20rpx 20rpx 40rpx;
    background: #fff;
    border-radius: 10rpx;
    box-shadow: 0px 0px 1rpx #fff;
    margin-bottom: 20rpx;
}
</style>
